# -*- coding: utf-8 -*-
# @Time : 2020/4/1 18:19
# @Author : hlikex
# @File : Run.py

from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.chrome.options import Options
from time import sleep
import urllib.request
import cv2
import numpy as np
import os
import logging

class Auto:

    def __init__(self):
        self.root_url = "https://mail.qq.com/"
        chrome_options = Options()
        # chrome_options.add_argument('--headless')
        self.driver = webdriver.Chrome(executable_path=os.getcwd() + "\drivers\chromedriver.exe",options=chrome_options)
        logging.basicConfig(format='%(asctime)s - %(pathname)s[line:%(lineno)d] - %(levelname)s: %(message)s',
                            level=logging.DEBUG)

        # 初始化读入QQ邮箱账号
        self.Users = []
        with open('User.txt', 'r') as f:
            for line in f:
                self.Users.append(line.strip("\n").split("----"))

    def isElementExist(self, by, value):
        try:
            self.driver.find_element(by=by, value=value)
            return True
        except:
            return False
        # 实现登录

    def get_login(self, user, password, twoPassword):

        self.driver.get(self.root_url)
        self.driver.switch_to.default_content()
        self.driver.find_element_by_id("qqLoginTab").click()
        self.driver.switch_to.frame(self.driver.find_element_by_id("login_frame"))

        # 判断本地是否登入QQ
        if self.isElementExist("id", "switcher_plogin"):
            self.driver.find_element_by_id("switcher_plogin").click()

        self.driver.find_element_by_id("u").clear()
        self.driver.find_element_by_id("u").send_keys(user)
        self.driver.find_element_by_id("p").clear()
        self.driver.find_element_by_id("p").send_keys(password)

        sleep(0.5)
        self.driver.find_element_by_id("login_button").click()

        # 检测是否有验证码
        if self.isElementExist("xpath", '//*[@id="tcaptcha_iframe"]'):
            logging.info("正在识别验证码请稍后。。。")
            #self.Slide()
        sleep(0.5)

        # 检测是否有二级密码
        if self.isElementExist("name", "pp"):
            logging.info("没有二级密码！！！")
            self.driver.find_element_by_name("pp").clear()
            self.driver.find_element_by_name("pp").send_keys(twoPassword)
            self.driver.find_element_by_id("btlogin").click()

    def run(self):

        for list in self.Users:
            # 二级密码登入
            print(list)
            if len(list) == 3:
                self.get_login(list[0],list[1],list[3])
            # 没有二级密码
            elif len(list) == 2:
                self.get_login(list[0],list[1],"")



if __name__ == '__main__':
    Auto()
    sleep(10000)